/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.commonres.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.AbsListView
import android.widget.ScrollView

import androidx.core.view.ViewCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

/**
 * Created by Mikes at 2019-11-15 19:57
 */
class FixedSwipeRefreshLayout : SwipeRefreshLayout {
    //实际需要滑动的child view
    private var mScrollUpChild: View? = null
    //自动加载更多的footer view
    private var loadMoreFooterView: LoadMoreFooterView? = null

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    fun setScrollUpChild(view: View) {
        mScrollUpChild = view
    }

    fun setLoadMoreFooterView(loadMoreFooterView: LoadMoreFooterView) {
        this.loadMoreFooterView = loadMoreFooterView
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        for(index in 0..childCount){
            val onlyOneChild = getChildAt(index)
            if(onlyOneChild is LoadMoreLQRRecyclerView){
                setLoadMoreFooterView(onlyOneChild.getLoadMoreFooterView())
            } else if(onlyOneChild is ScrollView){
                setScrollUpChild(onlyOneChild)
            }
        }
    }

    override fun canChildScrollUp(): Boolean {
        if (loadMoreFooterView != null) {
            //如果列表正在加载更多时，不能下拉刷新
            if (loadMoreFooterView!!.getCurrentLoadMoreState() === LoadMoreState.doing) {
                return true
            }
        }

        mScrollUpChild?.let {scrollView ->
            return if (android.os.Build.VERSION.SDK_INT < 14) {
                if (scrollView is AbsListView) {
                    scrollView.childCount > 0
                            && (scrollView.firstVisiblePosition > 0
                                || scrollView.getChildAt(0).top < scrollView.paddingTop
                            )
                } else {
                    ViewCompat.canScrollVertically(scrollView, -1) || scrollView.scrollY > 0
                }
            } else {
                scrollView.canScrollVertically(-1)
            }
        }

        return super.canChildScrollUp()
    }
}
